<template>
  <div class="enterprise-container">
    <div class="page-header">
      <div class="header-title">
        <h2>企业/承运商管理</h2>
        <span class="subtitle">管理系统中的企业和承运商信息</span>
      </div>
      <div class="header-actions">
        <el-button type="primary" @click="handleAddEnterprise">
          <el-icon><Plus /></el-icon>新增企业/承运商
        </el-button>
        <el-button @click="handleImport">
          <el-icon><Upload /></el-icon>批量导入
        </el-button>
        <el-button @click="handleExport">
          <el-icon><Download /></el-icon>导出数据
        </el-button>
      </div>
    </div>

    <!-- 搜索过滤区 -->
    <el-card class="filter-container">
      <el-form :inline="true" :model="filterForm" class="filter-form">
        <el-form-item label="企业名称">
          <el-input v-model="filterForm.name" placeholder="请输入企业名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="企业类型">
          <el-select v-model="filterForm.type" placeholder="请选择企业类型" clearable>
            <el-option label="客户" value="customer"></el-option>
            <el-option label="承运商" value="carrier"></el-option>
            <el-option label="供应商" value="supplier"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="资质状态">
          <el-select v-model="filterForm.status" placeholder="请选择资质状态" clearable>
            <el-option label="已认证" value="verified"></el-option>
            <el-option label="待审核" value="pending"></el-option>
            <el-option label="未通过" value="rejected"></el-option>
            <el-option label="已过期" value="expired"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>搜索
          </el-button>
          <el-button @click="resetFilter">
            <el-icon><RefreshRight /></el-icon>重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 企业列表 -->
    <el-card class="table-container">
      <el-table
        v-loading="tableLoading"
        :data="enterpriseList"
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="id" label="企业ID" width="100"></el-table-column>
        <el-table-column prop="name" label="企业名称" min-width="180"></el-table-column>
        <el-table-column prop="type" label="企业类型" width="120">
          <template #default="scope">
            <el-tag :type="getEnterpriseTypeTag(scope.row.type)">
              {{ getEnterpriseTypeLabel(scope.row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="creditCode" label="统一社会信用代码" width="200"></el-table-column>
        <el-table-column prop="contactPerson" label="联系人" width="120"></el-table-column>
        <el-table-column prop="contactPhone" label="联系电话" width="150"></el-table-column>
        <el-table-column prop="qualificationStatus" label="资质状态" width="120">
          <template #default="scope">
            <el-tag :type="getQualificationStatusTag(scope.row.qualificationStatus)">
              {{ getQualificationStatusLabel(scope.row.qualificationStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="expiryDate" label="资质到期日" width="120"></el-table-column>
        <el-table-column label="操作" width="220" fixed="right">
          <template #default="scope">
            <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="success" size="small" @click="handleVerify(scope.row)" v-if="scope.row.qualificationStatus === 'pending'">审核</el-button>
            <el-button type="warning" size="small" @click="handleRenew(scope.row)" v-if="scope.row.qualificationStatus === 'expired'">续期</el-button>
            <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        ></el-pagination>
      </div>
    </el-card>

    <!-- 新增/编辑企业对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增企业/承运商' : '编辑企业/承运商'"
      width="650px"
    >
      <el-form
        ref="enterpriseForm"
        :model="enterpriseForm"
        :rules="enterpriseRules"
        label-width="120px"
      >
        <el-form-item label="企业名称" prop="name">
          <el-input v-model="enterpriseForm.name" placeholder="请输入企业名称"></el-input>
        </el-form-item>
        <el-form-item label="企业类型" prop="type">
          <el-select v-model="enterpriseForm.type" placeholder="请选择企业类型" style="width: 100%">
            <el-option label="客户" value="customer"></el-option>
            <el-option label="承运商" value="carrier"></el-option>
            <el-option label="供应商" value="supplier"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="统一社会信用代码" prop="creditCode">
          <el-input v-model="enterpriseForm.creditCode" placeholder="请输入统一社会信用代码">
            <template #append>
              <el-button @click="verifyCreditCode">验证</el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="联系人" prop="contactPerson">
          <el-input v-model="enterpriseForm.contactPerson" placeholder="请输入联系人姓名"></el-input>
        </el-form-item>
        <el-form-item label="联系电话" prop="contactPhone">
          <el-input v-model="enterpriseForm.contactPhone" placeholder="请输入联系电话"></el-input>
        </el-form-item>
        <el-form-item label="联系邮箱" prop="contactEmail">
          <el-input v-model="enterpriseForm.contactEmail" placeholder="请输入联系邮箱"></el-input>
        </el-form-item>
        <el-form-item label="详细地址" prop="address">
          <el-input v-model="enterpriseForm.address" placeholder="请输入详细地址"></el-input>
        </el-form-item>
        <el-form-item label="资质文件" prop="qualificationFiles">
          <el-upload
            class="upload-demo"
            action="#"
            :http-request="uploadQualificationFiles"
            :file-list="enterpriseForm.qualificationFiles"
            multiple
            :limit="5"
          >
            <el-button type="primary">点击上传</el-button>
            <template #tip>
              <div class="el-upload__tip">
                请上传营业执照、经营许可证等资质文件，仅支持jpg/png/pdf文件，单个文件不超过10MB
              </div>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input
            v-model="enterpriseForm.remarks"
            type="textarea"
            rows="3"
            placeholder="请输入备注信息"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitEnterpriseForm">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 资质审核对话框 -->
    <el-dialog v-model="verifyDialogVisible" title="资质审核" width="600px">
      <el-form ref="verifyForm" :model="verifyForm" label-width="120px">
        <el-form-item label="企业名称">
          <span>{{ currentEnterprise?.name }}</span>
        </el-form-item>
        <el-form-item label="资质文件">
          <div class="qualification-files">
            <div v-for="(file, index) in currentEnterprise?.qualificationFiles" :key="index" class="file-item">
              <el-image
                v-if="isImage(file.name)"
                :src="file.url"
                :preview-src-list="getPreviewList()"
                fit="cover"
                class="file-preview"
              ></el-image>
              <div v-else class="file-icon" @click="previewFile(file)">
                <el-icon><Document /></el-icon>
                <span>{{ file.name }}</span>
              </div>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="审核结果" prop="status">
          <el-radio-group v-model="verifyForm.status">
            <el-radio label="verified">通过</el-radio>
            <el-radio label="rejected">不通过</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="有效期至" prop="expiryDate" v-if="verifyForm.status === 'verified'">
          <el-date-picker
            v-model="verifyForm.expiryDate"
            type="date"
            placeholder="选择有效期截止日期"
            style="width: 100%"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="审核意见" prop="comments">
          <el-input
            v-model="verifyForm.comments"
            type="textarea"
            rows="3"
            placeholder="请输入审核意见"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="verifyDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitVerifyForm">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Upload, Download, Search, RefreshRight, Document } from '@element-plus/icons-vue'

// 表格加载状态
const tableLoading = ref(false)

// 选中的企业
const selectedEnterprises = ref([])

// 分页配置
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 过滤表单
const filterForm = reactive({
  name: '',
  type: '',
  status: ''
})

// 企业表单
const enterpriseForm = reactive({
  id: '',
  name: '',
  type: '',
  creditCode: '',
  contactPerson: '',
  contactPhone: '',
  contactEmail: '',
  address: '',
  qualificationFiles: [],
  remarks: ''
})

// 企业表单验证规则
const enterpriseRules = {
  name: [
    { required: true, message: '请输入企业名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择企业类型', trigger: 'change' }
  ],
  creditCode: [
    { required: true, message: '请输入统一社会信用代码', trigger: 'blur' },
    { pattern: /^[0-9A-HJ-NPQRTUWXY]{2}\d{6}[0-9A-HJ-NPQRTUWXY]{10}$/, message: '统一社会信用代码格式不正确', trigger: 'blur' }
  ],
  contactPerson: [
    { required: true, message: '请输入联系人姓名', trigger: 'blur' }
  ],
  contactPhone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机号码格式不正确', trigger: 'blur' }
  ],
  contactEmail: [
    { required: false, message: '请输入联系邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ]
}

// 审核表单
const verifyForm = reactive({
  status: 'verified',
  expiryDate: '',
  comments: ''
})

// 对话框控制
const dialogVisible = ref(false)
const dialogType = ref('add') // 'add' 或 'edit'
const verifyDialogVisible = ref(false)
const currentEnterprise = ref(null)

// 企业列表数据
const enterpriseList = ref([
  {
    id: 'ENT-001',
    name: '北京物流科技有限公司',
    type: 'customer',
    creditCode: '91110105MA00BXUT2R',
    contactPerson: '张三',
    contactPhone: '13800138000',
    contactEmail: 'zhangsan@example.com',
    address: '北京市朝阳区建国路88号',
    qualificationStatus: 'verified',
    expiryDate: '2026-12-31',
    qualificationFiles: [
      { name: '营业执照.jpg', url: 'http://example.com/license.jpg' },
      { name: '经营许可证.pdf', url: 'http://example.com/permit.pdf' }
    ],
    remarks: '重要客户，优先处理'
  },
  {
    id: 'ENT-002',
    name: '上海运输集团有限公司',
    type: 'carrier',
    creditCode: '91310115MA00CXVT3S',
    contactPerson: '李四',
    contactPhone: '13900139000',
    contactEmail: 'lisi@example.com',
    address: '上海市浦东新区张江高科技园区',
    qualificationStatus: 'pending',
    expiryDate: '',
    qualificationFiles: [
      { name: '营业执照.jpg', url: 'http://example.com/license2.jpg' },
      { name: '道路运输许可证.pdf', url: 'http://example.com/transport_permit.pdf' }
    ],
    remarks: '新合作伙伴，需要审核'
  },
  {
    id: 'ENT-003',
    name: '广州货运服务有限公司',
    type: 'carrier',
    creditCode: '91440101MA00DXWT4T',
    contactPerson: '王五',
    contactPhone: '13700137000',
    contactEmail: 'wangwu@example.com',
    address: '广州市天河区珠江新城',
    qualificationStatus: 'expired',
    expiryDate: '2023-10-15',
    qualificationFiles: [
      { name: '营业执照.jpg', url: 'http://example.com/license3.jpg' }
    ],
    remarks: '资质已过期，需要续期'
  }
])

// 获取企业类型标签样式
const getEnterpriseTypeTag = (type) => {
  const typeMap = {
    'customer': 'success',
    'carrier': 'primary',
    'supplier': 'warning'
  }
  return typeMap[type] || 'info'
}

// 获取企业类型标签文本
const getEnterpriseTypeLabel = (type) => {
  const typeMap = {
    'customer': '客户',
    'carrier': '承运商',
    'supplier': '供应商'
  }
  return typeMap[type] || '未知'
}

// 获取资质状态标签样式
const getQualificationStatusTag = (status) => {
  const statusMap = {
    'verified': 'success',
    'pending': 'warning',
    'rejected': 'danger',
    'expired': 'info'
  }
  return statusMap[status] || 'info'
}

// 获取资质状态标签文本
const getQualificationStatusLabel = (status) => {
  const statusMap = {
    'verified': '已认证',
    'pending': '待审核',
    'rejected': '未通过',
    'expired': '已过期'
  }
  return statusMap[status] || '未知'
}

// 判断文件是否为图片
const isImage = (fileName) => {
  return /\.(jpg|jpeg|png|gif)$/i.test(fileName)
}

// 获取预览图片列表
const getPreviewList = () => {
  if (!currentEnterprise.value) return []
  return currentEnterprise.value.qualificationFiles
    .filter(file => isImage(file.name))
    .map(file => file.url)
}

// 预览文件
const previewFile = (file) => {
  window.open(file.url, '_blank')
}

// 验证统一社会信用代码
const verifyCreditCode = () => {
  if (!enterpriseForm.creditCode) {
    ElMessage.warning('请先输入统一社会信用代码')
    return
  }
  
  // 模拟API调用验证
  tableLoading.value = true
  setTimeout(() => {
    tableLoading.value = false
    ElMessage.success('验证通过，企业信息有效')
    // 实际应用中应该调用企业信用信息API获取企业信息并自动填充表单
  }, 1000)
}

// 处理表格选择变化
const handleSelectionChange = (selection) => {
  selectedEnterprises.value = selection
}

// 处理搜索
const handleSearch = () => {
  // 实际应用中应该调用API进行搜索
  tableLoading.value = true
  setTimeout(() => {
    tableLoading.value = false
    pagination.currentPage = 1
    ElMessage.success('搜索完成')
  }, 500)
}

// 重置过滤条件
const resetFilter = () => {
  Object.keys(filterForm).forEach(key => {
    filterForm[key] = ''
  })
  handleSearch()
}

// 处理新增企业
const handleAddEnterprise = () => {
  dialogType.value = 'add'
  Object.keys(enterpriseForm).forEach(key => {
    enterpriseForm[key] = key === 'qualificationFiles' ? [] : ''
  })
  dialogVisible.value = true
}

// 处理编辑企业
const handleEdit = (row) => {
  dialogType.value = 'edit'
  Object.keys(enterpriseForm).forEach(key => {
    enterpriseForm[key] = row[key]
  })
  dialogVisible.value = true
}

// 处理审核
const handleVerify = (row) => {
  currentEnterprise.value = row
  verifyForm.status = 'verified'
  verifyForm.expiryDate = new Date(new Date().setFullYear(new Date().getFullYear() + 1))
  verifyForm.comments = ''
  verifyDialogVisible.value = true
}

// 处理续期
const handleRenew = (row) => {
  currentEnterprise.value = row
  verifyForm.status = 'verified'
  verifyForm.expiryDate = new Date(new Date().setFullYear(new Date().getFullYear() + 1))
  verifyForm.comments = '资质续期'
  verifyDialogVisible.value = true
}

// 处理删除
const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确定要删除企业 "${row.name}" 吗？`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // 实际应用中应该调用API删除数据
    const index = enterpriseList.value.findIndex(item => item.id === row.id)
    if (index !== -1) {
      enterpriseList.value.splice(index, 1)
      ElMessage.success('删除成功')
    }
  }).catch(() => {
    // 取消删除
  })
}

// 处理导入
const handleImport = () => {
  ElMessage.info('导入功能开发中...')
}

// 处理导出
const handleExport = () => {
  if (selectedEnterprises.value.length === 0) {
    ElMessage.warning('请先选择要导出的企业')
    return
  }
  
  ElMessage.success(`已选择 ${selectedEnterprises.value.length} 家企业进行导出`)
  // 实际应用中应该调用API导出数据
}

// 上传资质文件
const uploadQualificationFiles = (options) => {
  // 模拟上传
  setTimeout(() => {
    const file = options.file
    enterpriseForm.qualificationFiles.push({
      name: file.name,
      url: URL.createObjectURL(file)
    })
    options.onSuccess()
  }, 500)
}

// 提交企业表单
const submitEnterpriseForm = () => {
  enterpriseForm.value.validate(valid => {
    if (valid) {
      // 实际应用中应该调用API保存数据
      if (dialogType.value === 'add') {
        // 新增企业
        const newEnterprise = {
          ...enterpriseForm,
          id: `ENT-${Math.floor(Math.random() * 1000).toString().padStart(3, '0')}`,
          qualificationStatus: 'pending',
          expiryDate: ''
        }
        enterpriseList.value.unshift(newEnterprise)
        ElMessage.success('添加企业成功，等待资质审核')
      } else {
        // 编辑企业
        const index = enterpriseList.value.findIndex(item => item.id === enterpriseForm.id)
        if (index !== -1) {
          enterpriseList.value[index] = { ...enterpriseList.value[index], ...enterpriseForm }
          ElMessage.success('更新企业信息成功')
        }
      }
      dialogVisible.value = false
    } else {
      return false
    }
  })
}

// 提交审核表单
const submitVerifyForm = () => {
  if (!verifyForm.status) {
    ElMessage.warning('请选择审核结果')
    return
  }
  
  if (verifyForm.status === 'verified' && !verifyForm.expiryDate) {
    ElMessage.warning('请选择有效期截止日期')
    return
  }
  
  // 实际应用中应该调用API保存审核结果
  const index = enterpriseList.value.findIndex(item => item.id === currentEnterprise.value.id)
  if (index !== -1) {
    enterpriseList.value[index].qualificationStatus = verifyForm.status
    enterpriseList.value[index].expiryDate = verifyForm.status === 'verified' 
      ? verifyForm.expiryDate.toISOString().split('T')[0]
      : ''
    
    ElMessage.success('审核完成')
    verifyDialogVisible.value = false
  }
}

// 处理分页大小变化
const handleSizeChange = (size) => {
  pagination.pageSize = size
  // 重新加载数据
}

// 处理页码变化
const handleCurrentChange = (page) => {
  pagination.currentPage = page
  // 重新加载数据
}

onMounted(() => {
  // 实际应用中应该调用API加载数据
  tableLoading.value = true
  setTimeout(() => {
    pagination.total = enterpriseList.value.length
    tableLoading.value = false
  }, 500)
})
</script>

<style scoped>
.enterprise-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-title {
  display: flex;
  flex-direction: column;
}

.header-title h2 {
  margin: 0;
  font-size: 22px;
  color: #303133;
}

.subtitle {
  font-size: 14px;
  color: #909399;
  margin-top: 5px;
}

.filter-container {
  margin-bottom: 20px;
}

.filter-form {
  display: flex;
  flex-wrap: wrap;
}

.table-container {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.qualification-files {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.file-item {
  width: 120px;
  height: 120px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  overflow: hidden;
  display: flex;
  justify-content: center;
  align-items: center;
}

.file-preview {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.file-icon {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  color: #409EFF;
}

.file-icon .el-icon {
  font-size: 32px;
  margin-bottom: 5px;
}

.file-icon span {
  font-size: 12px;
  text-align: center;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  width: 100px;
  padding: 0 5px;
}
</style>
